import React from "react";
import PropTypes from "prop-types";
import {getSearchGameList} from "@/api/JustGameInfo";
import _ from "lodash";
import {Col, Row} from "antd";
import {Container} from './style';
import JCard from "@/common/Card";
import {EmptyData} from "@/common/window/EmptyData";
import {toBase64} from "@/util/CodeUtils";
import {connect} from "react-redux";
import {getQueryVariable} from "@/util/global";

class SearchBox extends React.Component {
    constructor(props) {
        super(props);
        this.loadData = this.loadData.bind(this);

        this.state = {
            games: [],
            page: 1,
            size: 20,
            total: 0
        }
    }

    componentDidMount() {
        /* 如果发现URL中存在参数，则不在初始化时加载数据，因为SearchBar组件会更新props，造成重复加载 */
        if (!getQueryVariable("type") && !getQueryVariable("platform")) {
            this.loadData();
        }
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (!_.isEqual(this.props, prevProps)) {
            this.loadData();
        }
    }

    loadData() {
        let params = {
            page: this.state.page,
            size: this.state.size,
            types: this.props.typeArray,
            platforms: this.props.platformArray,
            keyword: this.props.keyword,
            orderBy: "viewCount",
        }
        console.log('params', params)
        getSearchGameList(params).then(res => {
            if (res.success) {
                this.setState({
                    games: res.data.rows,
                    total: res.data.total
                })
            }
        })
    }

    render() {
        return <Container>
            <Row gutter={[16, 16]} style={{padding: '10px 0'}}>
                {
                    this.state.games.length > 0 ?
                        this.state.games.map(game => {
                            return <Col span={4} key={game.id}>
                                <JCard height={"290px"}
                                       onClick={() => window._ROUTER_.push(`/game?id=${toBase64(game.id)}`)}
                                       info={game}
                                       title={game.cnName} description={game.enName}
                                       photo={game.image} video={game.videoUrl}/>
                            </Col>
                        })
                        :
                        <EmptyData/>
                }
            </Row>
        </Container>
    }


}

const mapStateToProps = (state) => {
    return {
        // searchValue: state.getIn(['header', 'searchValue']),
    }
};
SearchBox.propTypes = {
    platformArray: PropTypes.array,
    typeArray: PropTypes.array,
    keyword: PropTypes.string
}

export default connect(mapStateToProps, null)(SearchBox);
